<template>
    <el-dialog :title="isEdit ? '编辑讨论' : '新建讨论'" :visible.sync="dialogVisible" width="50%">
      <el-form :model="post" :rules="rules" ref="postForm" label-position="top">
        <el-form-item label="标题" prop="title">
          <el-input v-model="post.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="post.content" type="textarea" :rows="8" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </template>
  
  <script>
  export default {
    data() {
      return {
        dialogVisible: false,
        isEdit: false,
        post: {
          title: '',
          content: ''
        },
        rules: {
          title: [
            { required: true, message: '请输入标题', trigger: 'blur' },
            { min: 5, max: 50, message: '长度在 5 到 50 个字符', trigger: 'blur' }
          ],
          content: [
            { required: true, message: '请输入内容', trigger: 'blur' },
            { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      handleEdit(post) {
        this.isEdit = true;
        this.dialogVisible = true;
        this.post = post;
      },
      handleNew() {
        this.isEdit = false;
        this.dialogVisible = true;
        this.post = {
          title: '',
          content: ''
        };
      },
      handleSubmit() {
        this.$refs.postForm.validate(valid => {
          if (valid) {
            const url = this.isEdit ? '/post/update' : '/post/add';
            this.request.post(url, this.post)
              .then(response => {
                this.$message.success('保存成功');
                this.dialogVisible = false;
                this.$emit('refresh');
              })
              .catch(error => {
                console.error(error);
              });
          }
        });
      },
      handleCancel() {
        this.dialogVisible = false;
      }
    }
  }
  </script>
  